

#include "ds1307Driver.h"

#include "i2cDriver.h"

void rtcInit(void)
{
	i2cInit();
	i2cStart();
	i2cWrite(0xD0); // Address the RTC to write
	i2cWrite(0x07);
	i2cWrite(0x00);
	i2cStop();
}

void rtcSetTime(unsigned char h,unsigned char m, unsigned char s)
{
	i2cStart();
	i2cWrite(0xD0);
	i2cWrite(0);
	i2cWrite(s);
	i2cWrite(m);
	i2cWrite(h);
	i2cStop();
}

void rtcSetDate(unsigned char y, unsigned char m, unsigned char d)
{
	i2cStart();
	i2cWrite(0xD0);
	i2cWrite(0x04);
	i2cWrite(d);
	i2cWrite(m);
	i2cWrite(y);
	i2cStop();
}

void rtcGetDate(unsigned char * y, unsigned char * m, unsigned char * d)
{
	i2cStart();
	i2cWrite(0xD0);
	i2cWrite(0x04);
	i2cStop();

	i2cStart();
	i2cWrite(0xD1);

	*d = i2cRead(1);
	*m = i2cRead(1);
	*y = i2cRead(0);
	i2cStop();
	
}

// Convert binary coded decimal to normal decimal numbers
unsigned char bcdToDec(unsigned char val)
{
  return ( (val/16*10) + (val%16) );
}

void rtcGetTime(unsigned char * h, unsigned char * m, unsigned char * s)
{
	i2cStart();
	i2cWrite(0xD0);
	i2cWrite(0);
	i2cStop();

	i2cStart();
	i2cWrite(0xD1);

	* s = i2cRead(1);
	* m = i2cRead(1);
	* h = i2cRead(0);

	i2cStop();
}
